package com.qiaofang.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.google.common.collect.Lists;
import com.qiaofang.common.constant.DelFlagEnum;
import com.qiaofang.common.utils.StringUtil;
import com.qiaofang.constant.SystemIdEnum;
import com.qiaofang.constant.WxModelTemplateEnum;
import com.qiaofang.constant.WxModelTypeEnum;
import com.qiaofang.dto.WxConfigDTO;
import com.qiaofang.entity.Company;
import com.qiaofang.entity.CompanyWxConfig;
import com.qiaofang.entity.Subscription;
import com.qiaofang.entity.WxMsgModel;
import com.qiaofang.repository.CompanyWxConfigRepository;
import com.qiaofang.repository.SubscriptionRepository;
import com.qiaofang.repository.WxMsgModelRepository;
import com.qiaofang.service.WxConfigService;
import com.qiaofang.vo.WxConfigVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class WxConfigServiceImpl implements WxConfigService {

    /**
     * (微信配置,区分分销及案场助手2个系统, SystemIdEnum)
     */
    @Autowired
    private CompanyWxConfigRepository companyWxConfigRepository;

    /**
     * 模板消息总配置表
     */
    @Autowired
    private SubscriptionRepository subscriptionRepository;

    /**
     * 模板消息模板表
     */
    @Autowired
    private WxMsgModelRepository wxMsgModelRepository;

    @Override
    public void saveWxConfig(Company company, List<WxConfigDTO> wxConfigs) {
    	// 先遍历 systemId 一致的只保存一个
    	List<WxConfigDTO> undistinctWxConfigs = new ArrayList<>();
    	for (WxConfigDTO wxConfigDTO : wxConfigs) {
    		boolean distinctFlag = false;
    		for (WxConfigDTO wxConfigDTO2 : undistinctWxConfigs) {
    			if(wxConfigDTO2.getSystemId().equals(wxConfigDTO.getSystemId())) {
    				distinctFlag = true;
    			}
    		}
    		if(!distinctFlag) {
    			undistinctWxConfigs.add(wxConfigDTO);
    		}
		}
    	wxConfigs = undistinctWxConfigs;
        if (company != null && wxConfigs != null && wxConfigs.size() > 0) {
            boolean flag = false;
            List<CompanyWxConfig> companyWxConfigs = listCompanyWxConfig(company.getCompanyUuid());
            List<Subscription> subscriptions;
            List<WxMsgModel> wxMsgModels;
            if (companyWxConfigs != null && companyWxConfigs.size() > 0) {
                subscriptions = listSubscription(company.getId(), company.getCompanyUuid());
                wxMsgModels = listWxMsgModel(company.getId(), company.getCompanyUuid());
            } else {
                companyWxConfigs = Lists.newArrayList();
                subscriptions = Lists.newArrayList();
                wxMsgModels = Lists.newArrayList();
                flag = true;
            }
            if (flag) {
                //新增
                for (WxConfigDTO configDTO : wxConfigs) {
//                    if (wxConfigs.size() > 1) {
                        companyWxConfigs.add(createCompanyWxConfig(company, configDTO.getSystemId(), configDTO.getWeChatPush()));
                        Subscription subscription = createSubscription(company, configDTO, configDTO.getSystemId());
                        subscriptionRepository.save(subscription);
                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), configDTO.getReportTemplateId(), WxModelTypeEnum.NEW_REPORT, configDTO.getSystemId()));
                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), configDTO.getStatusChangeId(), WxModelTypeEnum.CHANGE_REPORT_STATUS, configDTO.getSystemId()));
                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), configDTO.getReviewRejectionId(), WxModelTypeEnum.AUDIT_REJECT, configDTO.getSystemId()));
                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), configDTO.getProjectApprovalId(), WxModelTypeEnum.PROJECT_AUDIT, configDTO.getSystemId()));
//                    } else {
//                        // 案场助手配置
//                        companyWxConfigs.add(createCompanyWxConfig(company, SystemIdEnum.ASSISTANT.getCode(), configDTO.getWeChatPush()));
//                        Subscription subscription = createSubscription(company, configDTO, SystemIdEnum.ASSISTANT.getCode());
//                        subscriptionRepository.save(subscription);
//                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), configDTO.getReportTemplateId(), WxModelTypeEnum.NEW_REPORT, SystemIdEnum.ASSISTANT.getCode()));
//                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), configDTO.getStatusChangeId(), WxModelTypeEnum.CHANGE_REPORT_STATUS, SystemIdEnum.ASSISTANT.getCode()));
//                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), configDTO.getReviewRejectionId(), WxModelTypeEnum.AUDIT_REJECT, SystemIdEnum.ASSISTANT.getCode()));
//                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), configDTO.getProjectApprovalId(), WxModelTypeEnum.PROJECT_AUDIT, SystemIdEnum.ASSISTANT.getCode()));
//                        // 分销助手配置
//                        companyWxConfigs.add(createCompanyWxConfig(company, SystemIdEnum.AGENCY_h5.getCode(), configDTO.getWeChatPush()));
//                        subscription = createSubscription(company, configDTO, SystemIdEnum.AGENCY_h5.getCode());
//                        subscriptionRepository.save(subscription);
//                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), configDTO.getReportTemplateId(), WxModelTypeEnum.NEW_REPORT, SystemIdEnum.AGENCY_h5.getCode()));
//                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), configDTO.getStatusChangeId(), WxModelTypeEnum.CHANGE_REPORT_STATUS, SystemIdEnum.AGENCY_h5.getCode()));
//                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), configDTO.getReviewRejectionId(), WxModelTypeEnum.AUDIT_REJECT, SystemIdEnum.AGENCY_h5.getCode()));
//                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), configDTO.getProjectApprovalId(), WxModelTypeEnum.PROJECT_AUDIT, SystemIdEnum.AGENCY_h5.getCode()));
//                    }
                }
            } else {
                //修改，修改时也可以新增微信端信息配置，会存在ID为空的配置, 也会删除
//            	String companyUuid = company.getCompanyUuid();
            	for (Subscription subscription : subscriptions) {
            		String systemId = subscription.getSystemId();
            		boolean removeFlag = true;
            		for (WxConfigDTO wxConfig : wxConfigs) {
						if(wxConfig.getSystemId() != null && 
								wxConfig.getSystemId().equals(systemId)) {
							removeFlag = false;
							break;
						}
					}
            		if(removeFlag) {
            			subscription.setDelFlag(DelFlagEnum.DEL.getNo());
            		}
				}
            	for (CompanyWxConfig companyWxConfig : companyWxConfigs) {
            		boolean removeFlag = true;
            		String systemId = companyWxConfig.getSystemId();
            		for (WxConfigDTO wxConfig : wxConfigs) {
						if(wxConfig.getSystemId() != null && 
								wxConfig.getSystemId().equals(systemId)) {
							removeFlag = false;
							break;
						}
					}
            		if(removeFlag) {
            			companyWxConfig.setDelFlag(DelFlagEnum.DEL.getNo());
            		}
                }
            	for (WxMsgModel wxMsgModel : wxMsgModels) {
            		boolean removeFlag = true;
            		String systemId = wxMsgModel.getSystemId();
            		for (WxConfigDTO wxConfig : wxConfigs) {
						if(wxConfig.getSystemId() != null && 
								wxConfig.getSystemId().equals(systemId)) {
							removeFlag = false;
							break;
						}
					}
            		if(removeFlag) {
            			wxMsgModel.setDelFlag(Integer.parseInt(DelFlagEnum.DEL.getNo()));
            		}
                }
                for (WxConfigDTO wxConfig : wxConfigs) {
                	// 如果是编辑时新增配置，则要使用添加
                	if(wxConfig.getId() == null) {
                		companyWxConfigs.add(createCompanyWxConfig(company, wxConfig.getSystemId(), wxConfig.getWeChatPush()));
                        Subscription subscription = createSubscription(company, wxConfig, wxConfig.getSystemId());
                        subscriptionRepository.save(subscription);
                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), wxConfig.getReportTemplateId(), WxModelTypeEnum.NEW_REPORT, wxConfig.getSystemId()));
                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), wxConfig.getStatusChangeId(), WxModelTypeEnum.CHANGE_REPORT_STATUS, wxConfig.getSystemId()));
                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), wxConfig.getReviewRejectionId(), WxModelTypeEnum.AUDIT_REJECT, wxConfig.getSystemId()));
                        wxMsgModels.addAll(createWxMsgModel(company, subscription.getId(), wxConfig.getProjectApprovalId(), WxModelTypeEnum.PROJECT_AUDIT, wxConfig.getSystemId()));
                        continue;
                	}
                    for (CompanyWxConfig companyWxConfig : companyWxConfigs) {
                    	
                        if (wxConfig.getId().equals(companyWxConfig.getId())) {
                            companyWxConfig.setDomain(company.getDomain());
                            companyWxConfig.setConfiged(wxConfig.getWeChatPush());
                            break;
                        }
                    }
                    for (Subscription subscription : subscriptions) {
                        if (StringUtil.equals(wxConfig.getSystemId(), subscription.getSystemId())) {
                        	subscription.setAppName(wxConfig.getAppName());
                            subscription.setAppId(wxConfig.getAppId());
                            subscription.setAppSecret(wxConfig.getAppSecret());
                            break;
                        }
                    }
                    for (WxMsgModel wxMsgModel : wxMsgModels) {
                        if (StringUtil.equals(wxConfig.getSystemId(), wxMsgModel.getSystemId())) {
                            if (WxModelTypeEnum.NEW_REPORT.checkModel(wxMsgModel.getWxModelType())) {
                                wxMsgModel.setWxModelMsgId(wxConfig.getReportTemplateId());
                            } else if (WxModelTypeEnum.CHANGE_REPORT_STATUS.checkModel(wxMsgModel.getWxModelType())) {
                                wxMsgModel.setWxModelMsgId(wxConfig.getStatusChangeId());
                            } else if (WxModelTypeEnum.AUDIT_REJECT.checkModel(wxMsgModel.getWxModelType())) {
                                wxMsgModel.setWxModelMsgId(wxConfig.getReviewRejectionId());
                            } else if (WxModelTypeEnum.PROJECT_AUDIT.checkModel(wxMsgModel.getWxModelType())) {
                                wxMsgModel.setWxModelMsgId(wxConfig.getProjectApprovalId());
                            }
                        }
                    }
                }
                subscriptionRepository.saveAll(subscriptions);
            }
            companyWxConfigRepository.saveAll(companyWxConfigs);
            wxMsgModelRepository.saveAll(wxMsgModels);
        }
    }

    private List<WxMsgModel> createWxMsgModel(Company company, Long subId, String msgId, WxModelTypeEnum wxModelTypeEnum, String SystemId) {
        List<WxMsgModel> wxMsgModels = Lists.newArrayList();
        List<WxModelTemplateEnum> list = WxModelTemplateEnum.listModelByModelId(wxModelTypeEnum.getCode());
        if (list != null) {
            for (WxModelTemplateEnum wxModelTemplateEnum : list) {
                WxMsgModel wxMsgModel = new WxMsgModel();
                wxMsgModel.setWxModelMsgId(msgId);
                wxMsgModel.setModelTitle(wxModelTemplateEnum.getName());
                wxMsgModel.setCompanyId(company.getId());
                wxMsgModel.setSubscriptionId(subId);
                wxMsgModel.setCompanyUuid(company.getCompanyUuid());
                wxMsgModel.setEnabled(1);
                wxMsgModel.setWxModelType(wxModelTemplateEnum.getType());
                wxMsgModel.setDelFlag(Integer.parseInt(DelFlagEnum.UNDEL.getNo()));
                wxMsgModel.setSystemId(SystemId);
                wxMsgModels.add(wxMsgModel);
            }
        }
        return wxMsgModels;
    }

    private Subscription createSubscription(Company company, WxConfigDTO wxConfigDTO, String SystemId) {
        if (company == null) {
            return null;
        }
        Subscription subscription = new Subscription();
        subscription.setAppId(wxConfigDTO.getAppId());
        subscription.setAppName(wxConfigDTO.getAppName());
        subscription.setAppSecret(wxConfigDTO.getAppSecret());
        subscription.setCompanyId(company.getId());
        subscription.setCompanyUuid(company.getCompanyUuid());
        subscription.setSystemId(SystemId);
        subscription.setDelFlag(DelFlagEnum.UNDEL.getNo());
        return subscription;
    }

    private CompanyWxConfig createCompanyWxConfig(Company company, String SystemId, String weChatPush) {
        if (company == null) {
            return null;
        }
        CompanyWxConfig companyWxConfig = new CompanyWxConfig();
        companyWxConfig.setDomain(company.getDomain());
        companyWxConfig.setCompanyUuid(company.getCompanyUuid());
        companyWxConfig.setConfiged(weChatPush);
        companyWxConfig.setDelFlag(DelFlagEnum.UNDEL.getNo());
        companyWxConfig.setSystemId(SystemId);
        return companyWxConfig;
    }

    @Override
    public List<WxConfigVO> getWxConfigs(Company company) {
        List<CompanyWxConfig> companyWxConfigs = listCompanyWxConfig(company.getCompanyUuid());
        List<WxConfigVO> vos = Lists.newArrayList();
        if (companyWxConfigs != null) {
            List<Subscription> subscriptions = listSubscription(company.getId(), company.getCompanyUuid());
            List<WxMsgModel> wxMsgModels = listWxMsgModel(company.getId(), company.getCompanyUuid());
            for (CompanyWxConfig wxConfig : companyWxConfigs) {
                WxConfigVO wxConfigVO = new WxConfigVO();
                wxConfigVO.setId(wxConfig.getId());
                wxConfigVO.setSystemId(wxConfig.getSystemId());
                //是否推送
                wxConfigVO.setWeChatPush(wxConfig.getConfiged());
                if (subscriptions != null) {
                    for (Subscription subscription : subscriptions) {
                        if (StringUtil.equals(wxConfig.getSystemId(), subscription.getSystemId())) {
                        	wxConfigVO.setAppName(subscription.getAppName());
                            wxConfigVO.setAppId(subscription.getAppId());
                            wxConfigVO.setAppSecret(subscription.getAppSecret());
                        }
                    }
                }
                if (wxMsgModels != null) {
                    for (WxMsgModel wxMsgModel : wxMsgModels) {
                        if (StringUtil.equals(wxConfig.getSystemId(), wxMsgModel.getSystemId())) {
                            if (WxModelTypeEnum.NEW_REPORT.checkModel(wxMsgModel.getWxModelType())) {
                                wxConfigVO.setReportTemplateId(wxMsgModel.getWxModelMsgId());
                            } else if (WxModelTypeEnum.CHANGE_REPORT_STATUS.checkModel(wxMsgModel.getWxModelType())) {
                                wxConfigVO.setStatusChangeId(wxMsgModel.getWxModelMsgId());
                            } else if (WxModelTypeEnum.AUDIT_REJECT.checkModel(wxMsgModel.getWxModelType())) {
                                wxConfigVO.setReviewRejectionId(wxMsgModel.getWxModelMsgId());
                            } else if (WxModelTypeEnum.PROJECT_AUDIT.checkModel(wxMsgModel.getWxModelType())) {
                                wxConfigVO.setProjectApprovalId(wxMsgModel.getWxModelMsgId());
                            }
                        }
                    }
                }
                vos.add(wxConfigVO);
            }
        } else {
            WxConfigVO wxConfigVO = new WxConfigVO();
            wxConfigVO.setAppId(company.getAppId());
            wxConfigVO.setAppSecret(company.getAppSecret());
        }
        return vos;
    }

    private List<CompanyWxConfig> listCompanyWxConfig(String companyUuid) {
        CompanyWxConfig companyWxConfig = new CompanyWxConfig();
        companyWxConfig.setCompanyUuid(companyUuid);
        companyWxConfig.setDelFlag(DelFlagEnum.UNDEL.getNo());
        List<CompanyWxConfig> companyWxConfigs = companyWxConfigRepository.findAll(Example.of(companyWxConfig));
        return companyWxConfigs;
    }

    private List<Subscription> listSubscription(Long companyId, String companyUuid) {
        Subscription subscription = new Subscription();
        subscription.setCompanyId(companyId);
        subscription.setCompanyUuid(companyUuid);
        subscription.setDelFlag(DelFlagEnum.UNDEL.getNo());
        List<Subscription> subscriptions = subscriptionRepository.findAll(Example.of(subscription));
        return subscriptions;
    }

    private List<WxMsgModel> listWxMsgModel(Long companyId, String companyUuid) {
        WxMsgModel wxMsgModel = new WxMsgModel();
        wxMsgModel.setCompanyId(companyId);
        wxMsgModel.setCompanyUuid(companyUuid);
        wxMsgModel.setDelFlag(Integer.parseInt(DelFlagEnum.UNDEL.getNo()));
        List<WxMsgModel> wxMsgModels = wxMsgModelRepository.findAll(Example.of(wxMsgModel));
        return wxMsgModels;
    }
}
